package arithmetic1.stack;

/*
    用数组实现栈
 */
public class Stack {
    //栈顶指针
    private int top;
    //栈底指针
    private int bottom;
    //栈的最大容量
    private int maxSize;
    //存储元素的数组
    int arr[];

    public Stack(int maxSize){
        //初始化栈
        this.maxSize=maxSize;
        arr=new int[maxSize];
        top=-1;
        bottom=-1;
    }

    //栈空
    public boolean isEmpty(){
        if (top==-1){
            return true;
        }else {
            return false;
        }
    }

    //栈满
    public boolean isFull(){
        if (top==maxSize-1){
            return true;
        }else {
            return false;
        }
    }

    //向栈中添加一个元素
    public void push(int num){
        if(isFull()){
            System.out.println("栈已满，无法添加");
            return;
        }else{
            top++;
            arr[top]=num;
            if(bottom==-1){
                bottom++;
            }
        }
    }

    //将栈顶的元素弹出
    public int pop(){
        if (isEmpty()){
            throw new RuntimeException("栈为空，没有元素可以删除");
        }else {
            int num=arr[top];
            top--;
            return num;
        }
    }

    //判断入栈的字符是不是运算符
    public static boolean isOperation(int ch){
        return ch=='+' || ch=='-' || ch=='*' || ch=='/';
    }

    public static boolean isOperation(String ch){
        return ch.equals("+") || ch.equals("-") || ch.equals("*") || ch.equals("*");
    }

    //返回运算符的优先级,数值越大优先级越高
    public static int priority(char ch){
        if(ch=='+' || ch=='-'){
            return 1;
        }else if (ch=='*' || ch=='/'){
            return 2;
        }else {
            return 0;
        }
    }

    //计算方法,num1为先出栈的元素，num2为后出栈的元素,oper是运算符
    public static int cul(int num1,int num2,char oper){
        int result=0;
        switch (oper){
            case '+':result=num1+num2; break;
            case '-':result=num2-num1; break;
            case '*':result=num1*num2; break;
            case '/':result=num2/num1; break;
        }
        return result;
    }

    //查看栈顶元素
    public int getTop(){
        return arr[top];
    }

    //返回栈的元素个数
    public int length(){
        return top+1;
    }

    //打印栈中的元素
    public void print(){
        int temp=top;
        for (int i=top;i>=0;i--){
            System.out.print(arr[i]+"\t");
        }
        System.out.println();
    }



}
